<?php

namespace App\Http\Controllers\Admin;

use App\Models\Agency;
use App\Models\Child;
use App\Models\Family;
use App\Models\User;
use Illuminate\Http\Request;

class ChildController extends BaseController
{
    /**
     * 按照平台和学校区分不同，展示不同范围的数据，
     * 显示形式相同。
     *
     * 平台展示所有
     * 学校展示本校学生
     *
     */

    public function list(Request $request)
    {
        $admin = $this->getAdmin();

        $isSchool = in_array(2, $admin->roleIds());

        $query = $request->only(['child_name', 'agency_id', 'user_id', 'stage', 'tool_id']);
        $users = collect();

        if ($isSchool){
            $query['agency_id'] = $admin->agency->id;
            $users = User::where("agency_id", $admin->agency->id)->get();
        }else{
            if (isset($query['agency_id'])){
                $users = User::where("agency_id", $query['agency_id'])->get();
            }
        }

        //平台
        $where = Child::selectQuery($query);
        $list = Child::where($where);
        if (!$isSchool){
            $list = $list->withTrashed();
        }
        $list = $list->orderBy('id', 'desc')->paginate(config('site.other.paginate'));
        $list->each(function (&$item){
            $item->durationtotal  = $item->histories()->sum("use_time");
            $item->firsttime = $item->histories()->value('start_time');
            $item->lasttime = $item->histories()->orderBy('id', 'desc')->value('start_time');
            $item->successnum = $item->histories()->where('result', 1)->count();
            $item->failnum = $item->histories()->where('result', 0)->count();
            $item->counttotal = $item->successnum + $item->failnum;
        });
        $list = $list->appends($query);
        $agencies = Agency::all();

        return backendView('child.list', compact('list', 'isSchool', 'admin', 'users', 'agencies', 'query'));
    }

    //
    public function index($user_id)
    {
        $admin = $this->getAdmin();

        $isSchool = in_array(2, $admin->roleIds());

        $user = User::find($user_id);
        if (empty($user)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }
        if ($isSchool) {
            $list = Child::where('user_id', $user_id)->orderBy('id', 'desc')->paginate(config('site.other.paginate'));
        } else {
            $list = Child::withTrashed()->where('user_id', $user_id)->orderBy('id', 'desc')->paginate(config('site.other.paginate'));
        }

        return backendView('child.index', compact('list', 'user', 'isSchool'));
    }

    public function add($user_id, Request $request)
    {

        $user = User::find($user_id);
        if (empty($user)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }

        if ($request->isMethod('post')) {
            $this->validate($request, [
                'name' => 'required|max:255',
                'birthday' => 'required|date',
                'sex' => 'required|in:0,1',
                'address' => 'required|max:255',
                'phone' => 'required|string|max:11',
            ], [], [
                'name' => __("Username"),
                'birthday' => __("Birthday"),
                'sex' => __("Sex"),
                'address' => 'required|max:255',
                'phone' => 'required|string|max:11',
            ]);

            $data = $request->only(['name', 'birthday', 'sex', 'address', 'phone']);
            $data['user_id'] = $user_id;
            $data['agency_id'] = $user->agency_id;
            if (Child::create($data)) {
                Family::firstOrCreate(['phone' => $data['phone']]);
                return redirect()->route('admin.child.index', ['user_id' => $user_id])->with('success', __('Create success'));
            }

            return back()->with('error', __('Create failed'))->withInput();
        } else {
            return backendView('child.add', compact('user'));
        }
    }

    public function edit($id, Request $request)
    {
        $child = Child::find($id);
        if (empty($child)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }

        if ($request->isMethod("post")) {
            $this->validate($request, [
                'name' => 'required|max:255',
                'birthday' => 'required|date',
                'sex' => 'required|in:0,1',
                'address' => 'required|max:255',
                'phone' => 'required|string|max:11',
            ], [], [
                'name' => __("Username"),
                'birthday' => __("Birthday"),
                'sex' => __("Sex"),
                'address' => 'required|max:255',
                'phone' => 'required|string|max:11',
            ]);
            $data = $request->only(['name', 'birthday', 'sex', 'address', 'phone']);

            if ($child->update($data)) {
                Family::firstOrCreate(['phone' => $data['phone']]);
                return redirect()->route('admin.child.index', ['user_id' => $child->user_id])->with('success', __('Edit success'));
            }

            return back()->with('error', __('Edit failed'));
        } else {

            return backendView('child.edit', compact('child'));
        }
    }

    //假删除，
    public function delete($id)
    {

        /*
                $assessment = Assessment::where("child_id", $id)->exists();
                $history = History::where("child_id", $id)->exists();

                if (count($assessment) || $history){
                    return back()->with('error', "学生有关联数据关联，无法删除");
                }
        */
        $admin = $this->getAdmin();

        if (in_array(2, $admin->roleIds())) {
            $child = Child::find($id);

            if (empty($child)) {
                return back()->with('error', __('The page you requested was not found'))->withInput();
            }
            //学校
            $status = $child->delete();
        } else {
            $child = Child::withTrashed()->find($id);

            if (empty($child)) {
                return back()->with('error', __('The page you requested was not found'))->withInput();
            }
            //平台
            $status = $child->forceDelete();
        }

        if ($status) {
            return back()->with('success', __('Delete success'));
        }

        return back()->with('error', __('Delete failed'));
    }

    public function view($id)
    {
        $child = Child::withTrashed()->find($id);

        if (empty($child)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }

        return backendView('child.view', compact('child'));
    }

}
